async function getConfig() {
  let endpoint = null;

  if ("undefined" == typeof document) { // background
    endpoint = await getEndpoint();
  } else { // content
    endpoint = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ action: 'getEndpoint' }, (response) => {
        resolve(response.endpoint);
      });
    });
  }
  const allConfig = await getAllConfig()

  return allConfig[endpoint];
}

async function getEndpoint() {
  const endpoint = await new Promise((resolve, reject) => {
    chrome.storage.local.get(['endpoint'], (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError.message);
      } else {
        resolve(result.endpoint);
      }
    });
  });

  return endpoint;
}

async function getAllConfig() {
  const configUrl = 'https://api.miraazzurra.com/amazon/google_sheet/content?spreadsheetId=1h1GFLPrR8cnAN2T3HYu1uQFNzstsqE9AiRTWjkl5H1Q&sheetName=alarm'
  const configTable = await fetch(configUrl).then(response => response.json())

  const titles = configTable[0]
  let res = {}
  
  for(let i = 1; i < configTable.length; i++) {
    let row = configTable[i]
    endpoint = row[0]
    res[endpoint] = {}

    for (let j = 0; j < titles.length; j++) {
      let title = titles[j]
      res[endpoint][title] = row[j]
    }
  }
  return res
}

async function getOrigin() {
  let endpoint = await getEndpoint()
  let origin = 'https://sellercentral.amazon.com'
  if (endpoint == 'MA-EU') {
    origin = 'https://sellercentral.amazon.co.uk'
  }

  return origin;
}
